<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%;">
    <div style="width: 100%;">
      <div style="display: flex; padding: 1px 15px;align-items: center;">
        <!-- 组件1 : 新增按钮 + 菜单名称 -->
        <el-button type="primary" @click="add">新建</el-button>
        <span style="margin-left: 10px; font-size: 20px;">员工</span>
        <div style="margin-left: auto;margin-right: auto;" class="search-operation-container">
          <!-- 搜索框 -->
          <ISearch :fieldsConfig="searchConfig || []" @searchCallBack="searchCallBack"
            v-show="multipleSelection.length == 0"></ISearch>
          <!-- 操作按钮组 -->
          <div v-show="multipleSelection.length != 0">
            <el-button type="primary" style="background-color: #f1edf0; color: #714B67;">
              {{ "(" + multipleSelection.length + ") 已选取" }}
            </el-button>
            <el-dropdown trigger="click" @command="handleOperationCommand">
              <el-button type="primary">
                <el-icon>
                  <Tools />
                </el-icon> 操作 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                  <el-dropdown-item command="export">导出</el-dropdown-item>
                  <el-dropdown-item command="archive">归档</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <!-- 按钮组-->
        <IdooButtonGroup :buttonConfigs="buttonGroupDatas" @clickCallBack="buttonGroupChange" is-active-style />
      </div>
    </div>
    <!-- 分割线 -->
    <el-divider border-style="dotted" />

    <div style="display: flex; height: 100vh;">
      <!-- 部门树 -->
      <div class="tree-container">
        <div class="tree-header">
          <el-icon>
            <Avatar />
          </el-icon>
          <span style="font-size: 15px; font-weight: 600;"> 部门 </span>
        </div>
        <div class="tree-wrapper">
          <el-tree ref="deptTreeRef" :data="deptTreeData" default-expand-all highlight-current
            :expand-on-click-node="false" :props="defaultProps" node-key="id" @node-click="treeClick">
            <template #default="{ data }">
              <span class="tree-node-title" :title="data.deptName"> {{ data.deptName }} </span>
              <!-- <span> {{ data.biz_count }} </span> -->
            </template>
          </el-tree>
        </div>
      </div>
      <!-- 表格列表 -->
      <div class="content-container">
        <div class="table-wrapper">
          <el-table ref="multipleTableRef" :data="tableData" style="width: 100%"
            @selection-change="handleSelectionChange"
            @row-click="(row: StaffForm) => router.push({ path: '/employess-staff/add', query: { id: row.id } })">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="staffName" label="员工姓名" width="180" />
            <el-table-column prop="staffCode" label="员工编号" width="180" />
            <el-table-column prop="staffTitleName" label="头衔" sortable width="180" />
            <el-table-column prop="staffPhone" label="电话号码" width="180" />
            <el-table-column prop="staffEmail" label="邮箱" />
            <el-table-column prop="staffJobAddress" label="工作地址" width="180" />
            <el-table-column prop="staffJobPost" label="工作岗位" width="180" />
            <el-table-column prop="manager" label="直属领导" width="180" />
            <el-table-column prop="staffAssensmentDate" label="最近考核日期" width="180" />
          </el-table>
          <!-- 分页 -->
          <div style="margin-top: 20px;">
            <IdooPagination :param="initPaginationParam" style="float:right ;margin-right: 25px;"
              @click-call-back="paginationCallBack"></IdooPagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';
import IdooPagination from '@/components/base/pagination/index.vue'
import { Tools, Avatar } from '@element-plus/icons-vue'
import ISearch from '@/components/base/search/index.vue'
import { Histogram, Grid } from '@element-plus/icons-vue'
import IdooButtonGroup from '@/components/base/button/buttonGroup/index.vue';
import type { ButtonGroupStructure } from '@/components/base/button/buttonGroup';
import type { PaginationStructure } from '@/components/base/pagination';
import router from '@/router';
import type { StaffForm } from '@/types/employess/staff/types';
import { _delStaffInfoByIds, _getStaffTableConfigeration, _getStaffTableList } from '@/api/generic/employess/staff/list-api';
import { _getDepartmentTree } from '@/api/generic/employess/department/list-api';
import type { DepartmentTree } from '@/types/employess/department/types';
import type { TableFieldType } from '@/types/table-configtypes';
import type { QueryCondition, QueryWrapper } from '@/types/wrappertypes';
import { ConditionsTypeEnums, OperatorTypeEnums, OrderEnums } from '@/types/wrapper-enums';
//列表勾选得内容
const multipleSelection = ref<StaffForm[]>([]);
//部门树数据
const deptTreeData = ref<DepartmentTree[]>([]);
//按钮组数据
const buttonGroupDatas = [{
  label: '',
  type : 'primary',
  icon: Grid, //图标
  disable: false, //是否禁用
  id :'list' , //click 回调会返回对应id
  defaultActiveId : true, //是否默认选中 仅在isUseActiveStyle 为true 时生效 ,组件中 默认为true
  hover:{
    title: '表格',
    content : '列表展示形式',
  }
},{
  label: '',
  type : 'primary',
  icon: Histogram, //图标
  disable: false, //是否禁用
  id :'card' , //click 回调会返回对应id
  defaultActiveId : false, //是否默认选中 仅在isUseActiveStyle 为true 时生效 ,组件中 默认为true
  hover: {
    title: '卡片',
    content : '',
  }
}]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const deptTreeRef = ref<any>(null);
//多功能搜索框内容配置
const searchConfig = ref<TableFieldType[]>([]);
//多功能搜索框查询条件
const searchCondition = ref<QueryCondition[]>([]);
const defaultProps = {
  children: 'children',
  label: 'label',
  id: 'id',
}
//左侧树默认选中的节点
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const currentNode = ref<any>(null);
//初始化分页参数
const initPaginationParam = ref<PaginationStructure>({ pageNum: 1, pageSize: 20, startNum: 1, totalNum: 0 });
//初始化查询条件
const queryWrapperCondition = ref<QueryWrapper>({
  page: initPaginationParam.value,//分页参数
  condition: [], //数据参数
  sort: [{ filed: 'dept_id', orderType: OrderEnums.WRAPPER_ORDER_DESC }, { filed: 'staff_name', orderType: OrderEnums.WRAPPER_ORDER_DESC },] //排序参数
});
//表格勾选
const handleSelectionChange = (val: []) => {
  multipleSelection.value = val
}
const tableData = ref<StaffForm[]>([]);

const treeClick = (val: object) => {
  const ids = findAllIds(val);
  console.log(ids);
  currentNode.value = val;
  const condition = createCurrentNodeConditions();
  queryWrapperCondition.value.condition = searchCondition.value?.concat(condition);
  refreshTableData();
}

/**
 * 构造左侧部门树的查询条件
 * @param root
 */
const createCurrentNodeConditions = () => {
  const ids = findAllIds(currentNode.value);
  if (ids.indexOf('all-node') != -1) {
    return [];
  }
  const condition = [{
    field: 'dept_id', // 字段名（对应后端实体字段）
    operator: OperatorTypeEnums.WRAPPER_CONDITION_TYPE_IN, // 操作符
    value: ids, // 值
    valueType: ConditionsTypeEnums.WRAPPER_CONDITION_TYPE_STRING, // 值类型（特殊类型需转换）
  }]//数据参数
  return condition;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const findAllIds = (root: any) => {
  let ids = [root.id];
  if (root.children) {
    console.log(root.children)
    for (const node of root.children) {
      ids = ids.concat(findAllIds(node));
    }
  }
  return ids;
}
const paginationCallBack = (obj: object) => {
  console.log(obj);
}

//按钮组回调
const buttonGroupChange = (callbackItem: ButtonGroupStructure) => {
  console.log(callbackItem)
  resetViewData();
}

const resetViewData = () => {
  //清空表格勾选数组
  multipleSelection.value = [];
}

//搜索框回调
const searchCallBack = (callbackItem: QueryCondition[]) => {
  console.log("搜索回调", callbackItem)
  callbackItem = callbackItem || [];
  searchCondition.value = callbackItem;
  initPaginationParam.value.startNum = 1
  initPaginationParam.value.pageNum = 1
  queryWrapperCondition.value.page = initPaginationParam.value;
  //带入左侧树的查询条件
  const condition_Dept = createCurrentNodeConditions();
  queryWrapperCondition.value.condition = callbackItem.concat(condition_Dept);
  console.log("wrapper:", queryWrapperCondition.value)
  refreshTableData();
}

const add = () => {
  router.push({
    path: '/employess-staff/add'
  })
}

onMounted(async () => {
  //默认一个查询全部的根节点
  const allNode: DepartmentTree = {
    id: 'all-node',
    children: [],
    deptName: '全部',
  }
  deptTreeData.value = [allNode]
  currentNode.value = allNode;
  //获取搜索框配置
  const tableConfigRes = await _getStaffTableConfigeration();
  searchConfig.value = tableConfigRes.data.selectorFieldsConfig || [];
  //获取部门树
  const departmentTreeRes = await _getDepartmentTree();
  if (departmentTreeRes.code == 200 && departmentTreeRes.data) {
    deptTreeData.value = deptTreeData.value.concat(departmentTreeRes.data);
  }
  //获取全部员工数据
  queryWrapperCondition.value = {
    page: { pageNum: 1, pageSize: 10 },
    condition: [], //数据参数
    sort: [{ filed: 'dept_id', orderType: OrderEnums.WRAPPER_ORDER_DESC }, { filed: 'staff_name', orderType: OrderEnums.WRAPPER_ORDER_DESC },] //排序参数
  };
  nextTick(() => {
    if (deptTreeRef.value) {
      deptTreeRef.value.setCurrentKey('all-node')
    }
  })
  refreshTableData();
});

//按照部门id查询
const refreshTableData = async () => {

  try {
    const res = await _getStaffTableList(queryWrapperCondition.value);
    console.log(res);
    if (res.code == 200 && res.message == 'success') {
      tableData.value = Array.isArray(res.data.rows) ? res.data.rows : [res.data.rows];
      if (initPaginationParam.value) {
        initPaginationParam.value.totalNum = res.data.total;
      }
      console.error(initPaginationParam.value);
    }
  } finally { }
}


const handleOperationCommand = async (command: string) => {
  console.log("操作命令:", command);
  console.log("选中的数据", multipleSelection.value)
  // 根据不同命令执行相应操作
  if (command === "delete") {
    // TODO: 删除操作逻辑
    if (multipleSelection.value) {
      const delIds = multipleSelection.value.map(item => item.id)
      const res = await _delStaffInfoByIds(delIds.join(','));
      if (res.code === 200) {
        refreshTableData();
      }
    }
  } else if (command === "export") {
    // TODO: 导出操作逻辑
  } else if (command === "archive") {
    // TODO: 归档操作逻辑
  }
}
</script>

<style scoped>
:deep(.el-divider--horizontal) {
  margin: 20px 0px 0px !important;
}

.main-left-area {
  border-right: 1px solid #dcdfe6;
  width: 20%;
}

.card {
  flex-basis: calc(25% - 10px);
  /* 考虑 10px 的间隙，每个卡片占 20% 宽度 */
  height: 150px;
  box-sizing: border-box;
}

:deep(.el-card) {
  overflow: visible !important;
}

:deep(.el-card__body) {
  justify-content: normal !important;
  align-items: normal !important;
  overflow: visible !important;
}

.card-content {
  height: 140px;
  /* 确保卡片内容填充整个卡片 */
  display: flex;
  justify-content: center;
  align-items: center;
  /* 使卡片内容居中显示 */
  overflow: visible;
}

.tree-node-title {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  max-width: 100px;
  /* 根据需要调整最大宽度 */
}

.tree-node-title:hover {
  overflow: visible;
  white-space: normal;
  position: relative;
}

.tree-node-title::after {
  content: attr(title);
  position: absolute;
  left: 0;
  top: 100%;
  background: #000;
  color: #fff;
  padding: 5px;
  display: none;
  z-index: 10;
  white-space: nowrap;
  /* 确保提示信息在一行内显示 */
}

.tree-node-title:hover::after {
  display: block;
}

/* 包装头像的容器；相对定位以便提示绝对定位 */
.avatar-container {
  position: relative;
  display: inline-block;
}

/* 隐藏的提示容器，鼠标悬停时显示 */
.avatar-tooltip {
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  /* 使提示覆盖在当前头像上 */
  transform: scale(1.5);
  transform-origin: top left;
  z-index: 1000;
  pointer-events: none;
  /* 防止提示层干扰鼠标事件 */
  transition: opacity 0.3s ease;
}

/* 鼠标悬停时显示提示 */
.avatar-container:hover .avatar-tooltip {
  opacity: 1;
}

.card-list-container {
  max-height: 800px;
  /* 根据实际情况，可以调整到合适的高度显示 5 行卡片 */
  overflow-y: auto;
  position: relative;
  padding-bottom: 30px;
  /* 为加载提示预留空间 */
}

.load-prompt {
  text-align: center;
  padding: 10px;
  background: #f9f9f9;
  color: #888;
  font-size: 14px;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
}

/* 自定义下拉菜单位置：菜单出现在按钮右侧 */
:deep(.operation-dropdown) {
  /* 取消默认定位（建议加 !important 确保覆盖） */
  left: auto !important;
  top: 0 !important;
  transform: translate(100%, 0) !important;
  /* 可根据需要调整偏移量 */
  margin: 0 !important;
}

/* 使下拉菜单宽度与操作按钮宽度一致 */
:deep(.operation-dropdown .el-dropdown-menu) {
  width: auto !important;
  min-width: 100% !important;
  box-sizing: border-box;
}

.search-operation-container {
  height: 32px;
  display: flex;
  align-items: center;
}

/**
高亮左侧树选中背景色
*/
:deep(.el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content) {
  background-color: #f1edf0 !important;
}


.tree-container {
  width: 250px;
  height: 100%;
  background: white;
  border-right: 1px solid #dcdfe6;
  transition: width 0.3s;
  overflow: hidden;
  flex-shrink: 0;
}

.tree-header {
  padding: 15px;
  border-bottom: 1px solid #dcdfe6;
}

.tree-title {
  font-size: 15px;
  font-weight: 600;
  margin-left: 8px;
}

.tree-wrapper {
  height: calc(100% - 52px);
  overflow-y: auto;
  padding: 8px;
}

.content-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 600px;
  overflow: hidden;
}

.table-wrapper {
  flex: 1;
  overflow: auto;
}

/* 表格滚动条样式 */
:deep(.el-table__body-wrapper) {
  overflow-x: auto;
}

/* 响应式处理 */
@media (max-width: 768px) {
  .tree-container {
    position: absolute;
    left: 0;
    z-index: 100;
    background: white;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  }
}
</style>
